# database.py

import asyncpg
from contextlib import asynccontextmanager
from typing import AsyncIterator, Optional
from config import settings

_pool: Optional[asyncpg.Pool] = None

async def get_pool_instance() -> asyncpg.Pool:
    global _pool
    if _pool is None:
        print("正在创建数据库连接池...")
        try:
            _pool = await asyncpg.create_pool(
                dsn=settings.SUPABASE_DB_URL,
                min_size=5,
                max_size=20
            )
            print("✅ 数据库连接池创建成功!")
        except Exception as e:
            print(f"❌ 创建数据库连接池失败: {e}")
            raise
    return _pool

@asynccontextmanager
async def get_db_pool() -> AsyncIterator[asyncpg.Pool]:
    pool = await get_pool_instance()
    try:
        yield pool
    finally:
        pass  # 不在这里关闭，由外部管理

@asynccontextmanager
async def get_db_connection() -> AsyncIterator[asyncpg.Connection]:
    pool = await get_pool_instance()
    async with pool.acquire() as conn:
        yield conn